package com.adkfp.interceptor;

import java.io.InputStream;
import java.util.Properties;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.adkfp.common.Constant;
import com.adkfp.common.UserRight;


public class AuthInterceptor implements HandlerInterceptor {

	@Override
	public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
			throws Exception {
		// TODO Auto-generated method stub
	}

	@Override
	public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
			throws Exception {
		// TODO Auto-generated method stub

	}

	@Override
	public boolean preHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2) throws Exception {
		System.out.println("========================");
		String servletPath = arg0.getServletPath();
		System.out.println(servletPath);
		HttpSession session = arg0.getSession();
		String UserName = (String) session.getAttribute(Constant.SESSION_USER_NAME_STRING);
		//System.out.println("----------bbb----------");
		Integer UserID =  (Integer) session.getAttribute(Constant.SESSION_USERID_LONG);
		//System.out.println("UserName"+UserName);
		if( UserName != null) {
			InputStream in =  this.getClass().getClassLoader().getResourceAsStream("/database.properties");
			Properties properties = new Properties();
			properties.load(in);
			//获取key对应的value值
			String dbdriver = properties.getProperty("jdbc.driverClass");//"com.mysql.jdbc.Driver");
			String dbhost =properties.getProperty("jdbc.jdbcUrl") ;//"jdbc:mysql://192.168.0.198:3306/qudao";
			String dbuser = properties.getProperty("jdbc.user","root");
			String dbpassword = properties.getProperty("jdbc.password", "123456");
			UserRight right = new UserRight(dbdriver,dbhost,dbuser,dbpassword);
			System.out.println("========================");
			System.out.println("正在校验权限!");
			boolean a=right.CheckRight(UserID, servletPath) ;
			if(a==false) {
				arg1.sendRedirect(arg0.getContextPath()+"/Yemian.jsp");
			}
			return a;
		}else {  
			return false;
		}

		//在这里加入权限控制代码
		//根据登录的UserID判断和控制是否有权限
		//请求的URL在servletPath中
		
	}

}
